<?php

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;
use \Workerman\Lib\Timer;

require_once 'vendor/Connection.php';
require_once 'vendor/redis.php';
require_once 'controller/controller.php';

//数据驱动

class Events {

    public static $controller;
    public static $db;
    public static $redis;

    //与start_gateway 只能一处生效
    public static function onWorkerStart($businessWorker) {
        // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
        static::$db = new \Workerman\MySQL\Connection('47.98.198.195', '3306', 'heyiwei', '123456', 'work_chat');
        //实例话redis链接
        $config = array('master' => array('ip' => '47.98.198.195', 'host' => 9736));
        //实例话 静态redis
        self::$redis = new redis_connnect($config['master'], 'heyiwei');
        //实例话 常用公用方法
        static::$controller = new controller(static::$db, self::$redis);
        //定时检测群，没动静的关闭
        Timer::add(5, function() {
            $all_group_list = Gateway::getAllGroupIdList();
            foreach ($all_group_list as $group_name) {
                //当前分组在线成连接数
                $all_num = Gateway::getClientCountByGroup($group_name);
                if ($all_num < 1) {
                    //没人直接关闭
                    Gateway::ungroup($group_name);
                }
            }
        });
        //定时任务异步处理聊天记录
        
    }

    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $message) {
        // 客户端传递的是json数据 不是json的再见
        $message_data = json_decode($message, true);
        print_r($message_data);
        if (empty($message_data) || empty($message_data['type'])) {
            $rs['status'] = 'false';
            $rs['msg'] = '数据格式有误';
            Gateway::sendToClient($client_id, json_encode($rs));
            //断开单人的链接  测试阶段 不要打开
            //Gateway::closeClient($client_id);
            return;
        }
        //检测用户基本信息,不存在的未登录
        if ($message_data['type'] != 'ping') {
            $user_token = $message_data['token'];
            if (empty($user_token)) {
                $rs['status'] = 'false';
                $rs['msg'] = '数据没有带token';
                Gateway::sendToClient($client_id, json_encode($rs));
                return;
            }
            $user_encode_info = self::$redis->get($user_token);
            if (empty($user_encode_info)) {
                $rs['status'] = 'false';
                $rs['msg'] = '滚去登录吧';
                Gateway::sendToClient($client_id, json_encode($rs));
                return;
            }
            //当前用户信息
            $user_info = json_decode($user_encode_info, TRUE)['user_info'];
            $user_id = $user_info['id'];
        }

        // 根据类型执行不同的业务
        switch ($message_data['type']) {
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'ping':
                //接受心跳 
                return;
            case 'login':
                //绑定用户id与用户的client_id  绑定后后面直接使用 $uid 发送信息
                Gateway::bindUid($client_id, $user_id);
                $rs_msg['type'] = 'login';
                $rs_msg['status'] = 'true';
                $rs_msg['msg'] = '成功';
                Gateway::sendToClient($client_id, json_encode($rs_msg));
                return;
            case 'chat_message':
                //聊天信息  发送方 接收方   类型包括（friend/好友   group/群）
                $from = $message_data['data']['mine'];
                $to = $message_data['data']['to'];
                $type = $to['type'];
                if ($type == 'friend') {
                    $friend_id = $to['id'];
                    //检测好友是否在线
                    if (!Gateway::isUidOnline($friend_id)) {
                        echo 'buzaixian';
                    }
                    $rs['type'] = 'chat_msg';
                    $rs['chat_type'] = 'friend';
                    $rs['data'] = $from;
                    //给好友发信息
                    Gateway::sendToUid($friend_id, json_encode($rs));
                }
                if ($type == 'group') {
                    $group_id = $to['id'];
                    $rs['type'] = 'chat_msg';
                    $rs['chat_type'] = 'group';
                    //发送的人
                    $rs['from_id'] = $from['id'];
                    $rs['group_id'] = $group_id;
                    $rs['data'] = $from;
                    //给群用户发信息  不包括自己
                    Gateway::sendToGroup($group_id, json_encode($rs));
                }
                return;
            case 'join_group':
                // 把房间号昵称放到session中
                $group_id = $message_data['group_id'];
                $user_name = $user_info['nick_name'];
                //当前群人员$client_id列表 //如果当前用户在分组里面不做任何处理
                $group_user_list = Gateway::getClientIdListByGroup($group_id);
                if (in_array($client_id, $group_user_list)) {
                    echo 'Already grouped, no need to join';
                    return;
                }
                //操作当前用户session
                $_SESSION['room_id'] = $group_id;
                $_SESSION['nick_name'] = $user_name;
                //通知当前在线的群友，xx进入聊天室 
                $new_message = array('type' => 'join_group', 'user_name' => $user_name, 'group_id' => $group_id);
                //通知所有群员有人加入
                Gateway::sendToGroup($group_id, json_encode($new_message));
                //当前用户加入群聊
                Gateway::joinGroup($client_id, $group_id);
                return;
            default :
                //不带类型的统统滚蛋
                $rs['msg'] = '你想干啥';
                Gateway::sendToClient($client_id, json_encode($rs));
                //断开单人的链接
//                Gateway::closeClient($client_id);
                break;
        }
    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id) {
        // debug
//        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";
        echo "{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']}" . date('H-i-s', time()) . " is lose \n";
        // 从房间的客户端列表中删除
        if (isset($_SESSION['room_id'])) {
            $room_id = $_SESSION['room_id'];
            $new_message = array('type' => 'logout', 'from_client_id' => $client_id, 'from_client_name' => $_SESSION['client_name'], 'time' => date('Y-m-d H:i:s'));
            Gateway::sendToGroup($room_id, json_encode($new_message));
        }
    }

    //回复信息
    public static function send_msg($client_id = '', $status = '-1', $data = '') {
        $msg['status'] = $status;
        $msg['data'] = $data;
        $msg['msg'] = '';
        if ($status == -1) {
            $msg['data'] = '';
            $msg['msg'] = $data;
        }
        Gateway::sendToClient($client_id, json_encode($msg));
    }

}
